﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Drawing;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using System.Resources;
using System.Reflection;
using STLGROUP.Layers.DataAccessLayers;
using STLGROUP.Layers.Presentations.FormBase;
using STLGROUP.Layers.Common;

namespace STLGROUP.Layers.Common
{
    public class UICommon
    {
        
        #region Variables

        private static ResourceManager _resourceManager = STLGROUP.Layers.Properties.Resources.ResourceManager;
        public static ACL_TaiKhoan CurrentUserInfo;

        #endregion

        #region Methods about Image

        public static Image resizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (Image)b;
        }

        public static string AddImage(string sourcePathImage, string path, string destPathFolderImage, string imageName, long fileSize)
        {
            string destPathImage = "";

            if (string.IsNullOrEmpty(sourcePathImage))
            {
                throw new Exception("Vui lòng chọn file");
            }
            else
            {
                try
                {
                    Image img = Image.FromFile(sourcePathImage);
                    FileInfo fileInfo = new FileInfo(sourcePathImage);
                    imageName += fileInfo.Extension;
                    destPathImage = destPathFolderImage + "\\" + imageName;

                    if (fileInfo.Length <= fileSize)
                    {
                        File.Copy(sourcePathImage, path + destPathImage, true);
                    }
                    else
                    {
                        throw new Exception("Vui lòng chọn file có dung lượng  <= " + fileSize.ToString() + "Byte");
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                return destPathImage;
            }
        }

        public static Image AddImage(string sourcePathImage, long fileSize)
        {
            Image img = null;

            if (string.IsNullOrEmpty(sourcePathImage))
            {
                throw new Exception("Vui lòng chọn file hình ảnh");
            }
            else
            {
                try
                {
                    img = Image.FromFile(sourcePathImage);
                    FileInfo fileInfo = new FileInfo(sourcePathImage);

                    if (fileInfo.Length <= fileSize)
                    {
                        return img;
                    }
                    else
                    {
                        throw new Exception("Vui lòng chọn file có dung lượng  <= " + fileSize.ToString() + "Byte");
                    }

                }
#if DEBUG
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return null;
                }
#else
                catch
                {
                    return null;
                }
#endif
            }
        }

        public static void ShowImage(string pathImage, PictureBox pic)
        {
            try
            {
                pic.Image = Image.FromFile(pathImage);
            }
            catch (Exception)
            {
                pic.Image = null;
            }
        }

        public static void ShowImage(Image image, PictureBox pic)
        {
            try
            {
                pic.Image = image;
            }
            catch (Exception)
            {
                pic.Image = null;
            }
        }

        /// <summary>
        /// convert image to byte array
        /// </summary>
        /// <param name="imageIn"></param>
        /// <returns></returns>
        /// <author>viet sang</author>
        public static byte[] ImageToByteArray(System.Drawing.Image imageIn)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                return ms.ToArray();
            }
            catch
            {
                return null;
            }   
        }

        /// <summary>
        /// convert byte array to image
        /// </summary>
        /// <param name="byteArrayIn"></param>
        /// <returns></returns>
        /// <author>viet sang</author>
        public static Image ByteArrayToImage(byte[] byteArrayIn)
        {
            try
            {
                MemoryStream ms = new MemoryStream(byteArrayIn);
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }
            catch
            {
                return null;
            }              
        }

        #endregion

        #region Method MaHoa

        public static string Encryption(string sourceString)
        {
            sourceString = sourceString.TrimEnd();

            MD5 md5Hasher = MD5.Create();

            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(sourceString));

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }

        public static bool Decoding(string input, string sourceString)
        {
            string hashOfInput = Encryption(input);

            return hashOfInput == sourceString;
        }

        public static void ChangeConnectionString(string strConn)
        {
            Configuration _config = ConfigurationManager.OpenExeConfiguration(
                       ConfigurationUserLevel.None);

            //the full name of the connection string can be found in the app.config file
            // in the "name" attribute of the connection string
            // _config.ConnectionStrings.ConnectionStrings[FULL NAME OF CONNECTION STRING HERE].ConnectionString = strConn;
            _config.ConnectionStrings.ConnectionStrings["QuanLyBanHangEntities"].ConnectionString = strConn;
            //Save to file
            _config.Save(ConfigurationSaveMode.Modified);

            //force changes to take effect so that we can start using
            //this new connection string immediately
            ConfigurationManager.RefreshSection(_config.ConnectionStrings.SectionInformation.Name);
            //Properties.Settings.Default.Reload();
        }

        #endregion
        
        #region Show messeges

        public static void ShowMessgeString(string msg, string caption)
        {
            MessageBox.Show(msg, caption,MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        public static void ShowMessgeString(string msg, string caption, MessageBoxButtons buttom, MessageBoxIcon icon)
        {
            MessageBox.Show(msg, caption, buttom, icon);
        }

        public static void ShowMessegeInfo(string IDMessege, params string[] pParameters)
        {
            MessageBox.Show(GetString(IDMessege, pParameters), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void ShowMessegeIsNotNull(string IDMessege = Const.MSG_IS_NOT_NULL, params string[] pParameters)
        {
            MessageBox.Show(GetString(IDMessege, pParameters), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public static void ShowMessegeDataNotFound(string IDMessege = Const.MSG_DATA_NOT_FOUND, params string[] pParameters)
        {
            MessageBox.Show(GetString(IDMessege, pParameters), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// Get string
        /// </summary>
        /// <param name="pMessageID"></param>
        /// <param name="pParameter"></param>
        /// <returns></returns>
        public static string GetString(string pMessageID, params string[] pParameter)
        {
            string message = string.Empty;

            if (pParameter != null)
            {
                message = string.Format(GetString(pMessageID), pParameter);
            }
            else
            {
                message = GetString(pMessageID);
            }

            return message;
        }

        public static string GetString(string pMessageID)
        {
            // Resource is null
            if (_resourceManager == null)
            {
                throw new Exception("Resource wasn't initilize");
            }

            // Get string from resource
            string message = _resourceManager.GetString(pMessageID);

            return message;
        }

        #endregion

        #region Properties

        //public DateTime GetServerDate()
        //{
        //    return DateTime.Now;
        //}

        #endregion

        #region Public methods

        public static DateTime GetDateTime()
        {
            return DateTime.Now;
        }

        public static void AddTrackingColumn(STLGROUP.Controls.STLDataGridView grid)
        {
            System.Windows.Forms.DataGridViewImageColumn TrackingState = new DataGridViewImageColumn();
            TrackingState.DataPropertyName = "TrackingState";
            TrackingState.HeaderText = string.Empty;
            TrackingState.Name = "TrackingState";
            TrackingState.ReadOnly = true;
            TrackingState.Width = 24;
            TrackingState.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            TrackingState.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;

            grid.Columns.Insert(0, TrackingState);
        }

        public static void ShowDataNotFound(STLGROUP.Controls.STLDataGridView grid, STLGROUP.Controls.STLLabel lbl,bool isShow)
        {
            if (isShow)
            {
                lbl.Visible = true;
                lbl.Text = "Không tìm thấy dữ liệu";
                lbl.Size = new System.Drawing.Size(grid.Size.Width, 30);
            }
            else
            {
                lbl.Visible = false;
            }
        }

        public static string NumberToString(double number)
        {
            string s = number.ToString("#");
            string[] so = new string[] { "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín" };
            string[] hang = new string[] { "", "nghìn", "triệu", "tỷ" };
            int i, j, donvi, chuc, tram;
            string str = " ";
            bool booAm = false;
            double decS = 0;
            //Tung addnew
            try
            {
                decS = Convert.ToDouble(s.ToString());
            }
            catch
            {
            }
            if (decS < 0)
            {
                decS = -decS;
                s = decS.ToString();
                booAm = true;
            }
            i = s.Length;
            if (i == 0)
                str = so[0] + str;
            else
            {
                j = 0;
                while (i > 0)
                {
                    donvi = Convert.ToInt32(s.Substring(i - 1, 1));
                    i--;
                    if (i > 0)
                        chuc = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        chuc = -1;
                    i--;
                    if (i > 0)
                        tram = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        tram = -1;
                    i--;
                    if ((donvi > 0) || (chuc > 0) || (tram > 0) || (j == 3))
                        str = hang[j] + str;
                    j++;
                    if (j > 3) j = 1;
                    if ((donvi == 1) && (chuc > 1))
                        str = "một " + str;
                    else
                    {
                        if ((donvi == 5) && (chuc > 0))
                            str = "lăm " + str;
                        else if (donvi > 0)
                            str = so[donvi] + " " + str;
                    }
                    if (chuc < 0)
                        break;
                    else
                    {
                        if ((chuc == 0) && (donvi > 0)) str = "lẻ " + str;
                        if (chuc == 1) str = "mười " + str;
                        if (chuc > 1) str = so[chuc] + " mươi " + str;
                    }
                    if (tram < 0) break;
                    else
                    {
                        if ((tram > 0) || (chuc > 0) || (donvi > 0)) str = so[tram] + " trăm " + str;
                    }
                    str = " " + str;
                }
            }
            if (booAm) str = "Âm " + str;
            return UppercaseFirst(str + "đồng");
        }

        public static string UppercaseFirst(string s)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            // Return char and concat substring.
            return char.ToUpper(s[0]) + s.Substring(1);
        }

        /// <summary>
        /// Show popup
        /// </summary>
        /// <param name="frmPopup"> form show </param>
        /// <param name="danhMuc">Enum danh muc</param>
        /// <param name="cboSource">cbo changed data </param>
        /// <param name="colBinding"> column on gird chang data when combobox change data</param>
        public static void ShowPopup(frmManager frmPopup,StructsEnums.EnumDanhMuc danhMuc, STLGROUP.Controls.STLCombobox cboSource, DataGridViewComboBoxColumn colBinding)
        {
            //frmPopup = new frmCatalogBase();
            frmPopup.ShowDialog();
            QuanLyBanHangEntities context = new QuanLyBanHangEntities();

            switch (danhMuc)
            {
                case StructsEnums.EnumDanhMuc.TinhThanh:
                    List<DM_TinhThanh> lstData = context.DM_TinhThanh.ToList();
                    cboSource.DataSource = lstData;
                    cboSource.SelectedValue = lstData.Count > 0 ? context.DM_TinhThanh.Max(s => s.IDTinhThanh) : 0;
                    colBinding.DataSource = lstData;
                    break;

                case StructsEnums.EnumDanhMuc.ChucVu:
                    break;

                case StructsEnums.EnumDanhMuc.NhaCungCap:
                    List<DT_NhaCungCap> lstNCC = context.DT_NhaCungCap.ToList();
                    cboSource.DataSource = lstNCC;
                    cboSource.SelectedValue = lstNCC.Count > 0 ? context.DT_NhaCungCap.Max(s => s.IDNhaCungCap) : 0;
                    colBinding.DataSource = lstNCC;
                    break;

                case StructsEnums.EnumDanhMuc.LoaiSanPham:
                    List<DM_LoaiSanPham> lstLSP = context.DM_LoaiSanPham.ToList();
                    cboSource.DataSource = lstLSP;
                    cboSource.SelectedValue = lstLSP.Count > 0 ? context.DM_LoaiSanPham.Max(s => s.IDLoaiSanPham) : 0;
                    colBinding.DataSource = lstLSP;
                    break;

                case StructsEnums.EnumDanhMuc.DanToc:
                    List<DM_DanToc> lstDT = context.DM_DanToc.ToList();
                    cboSource.DataSource = lstDT;
                    cboSource.SelectedValue = lstDT.Count > 0 ? context.DM_DanToc.Max(s => s.IDDanToc) : 0;
                    colBinding.DataSource = lstDT;
                    break;

                case StructsEnums.EnumDanhMuc.TonGiao:
                    List<DM_TonGiao> lstTG = context.DM_TonGiao.ToList();
                    cboSource.DataSource = lstTG;
                    cboSource.SelectedValue = lstTG.Count > 0 ? context.DM_TonGiao.Max(s => s.IDTonGiao) : 0;
                    colBinding.DataSource = lstTG;
                    break;

                case StructsEnums.EnumDanhMuc.PhongBan:
                    List<DM_PhongBan> lstPB = context.DM_PhongBan.ToList();
                    cboSource.DataSource = lstPB;
                    cboSource.SelectedValue = lstPB.Count > 0 ? context.DM_PhongBan.Max(s => s.IDPhongBan) : 0;
                    colBinding.DataSource = lstPB;
                    break;

                case StructsEnums.EnumDanhMuc.LoaiNhanVien:
                    List<DM_LoaiNhanVien> lstLNV = context.DM_LoaiNhanVien.ToList();
                    cboSource.DataSource = lstLNV;
                    cboSource.SelectedValue = lstLNV.Count > 0 ? context.DM_LoaiNhanVien.Max(s => s.IDLoaiNhanVien) : 0;
                    colBinding.DataSource = lstLNV;
                    break;
                case StructsEnums.EnumDanhMuc.ChuongTrinhKhuyenMai:
                    List<KM_ChuongTrinhKhuyenMai> lstKM = context.KM_ChuongTrinhKhuyenMai.ToList();
                    cboSource.DataSource = lstKM;
                    cboSource.SelectedValue = lstKM.Count > 0 ? context.KM_ChuongTrinhKhuyenMai.Max(s => s.IDChuongTrinhKM) : 0;
                    colBinding.DataSource = lstKM;
                    break;
            }
        }

        #endregion

        public System.Data.EntityState EntityState { get; set; }

        public static object DT_TinhThanh { get; set; }
    }
}
